// 游戏主文件

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', () => {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const roomId = urlParams.get('roomId');
    const playerName = urlParams.get('playerName');
    // 移除客户端颜色生成，颜色将由服务器分配
    
    if (!roomId) {
        alert('房间ID不存在，请返回首页重新加入房间');
        window.location.href = '/index.html';
        return;
    }
    
    // 获取游戏画布
    const canvas = document.getElementById('gameCanvas');
    
    // 根据设备屏幕大小调整画布尺寸
    function resizeCanvas() {
        const container = document.querySelector('.game-container');
        
        // 获取窗口尺寸
        const windowWidth = window.innerWidth;
        const windowHeight = window.innerHeight;
        
        // 设置canvas尺寸为窗口大小
        canvas.width = windowWidth;
        canvas.height = windowHeight;
        
        // 确保canvas元素可见
        canvas.style.display = 'block';
        canvas.style.backgroundColor = '#EEEEEE';
        
        // 通知渲染系统画布尺寸已更改
        // 修复：确保world变量已定义且已初始化
        if (window.world && typeof window.world !== 'undefined' && window.world.systems) {
            for (const system of window.world.systems) {
                if (system instanceof RenderSystem) {
                    system.onCanvasResize();
                }
            }
        }
    }
    
    // 初始设置画布尺寸
    resizeCanvas();
    
    // 监听窗口大小变化
    window.addEventListener('resize', resizeCanvas);
    
    // 显示玩家信息
    document.getElementById('playerName').textContent = playerName;
    document.getElementById('roomId').textContent = roomId;
    
    // 连接Socket.io服务器
    const socket = io();
    let playerId = null;
    
    // 获取或创建持久化的玩家ID
    const persistentPlayerId = PlayerIdManager.getOrCreatePlayerId();
    
    // 创建游戏世界
    const world = new World(canvas.width, canvas.height);
    
    // 添加系统
    world.addSystem(new InputSystem(world));
    world.addSystem(new CollisionSystem(world));
    world.addSystem(new RenderSystem(world, canvas));
    
    // 连接成功
    socket.on('connect', () => {
        console.log('已连接到服务器');
        playerId = socket.id;
        
        // 初始化游戏世界
        world.init(socket, playerId);
        
        // 加入房间，传递持久化的玩家ID
        socket.emit('joinRoom', {
            roomId,
            playerName,
            persistentId: persistentPlayerId
        });
    });
    
    // 加入房间成功
    socket.on('joinedRoom', (data) => {
        console.log('成功加入房间:', data);
        document.getElementById('waitingMessage').style.display = 'block';
    });
    
    // 游戏开始
    socket.on('gameStarted', () => {
        console.log('游戏开始');
        document.getElementById('waitingMessage').style.display = 'none';
        startGameLoop();
    });
    
    // 游戏结束
    world.on('gameOver', ({ winnerId }) => {
        if (winnerId === playerId) {
            // 显示胜利对话框
            const victoryDialog = document.getElementById('victoryDialog');
            victoryDialog.style.display = 'block';
            
            // 添加返回房间列表按钮的点击事件
            document.getElementById('returnToRoomList').addEventListener('click', () => {
                // 通知服务器玩家离开房间
                socket.emit('leaveRoom', { roomId });
                window.location.href = '/rooms.html';
            });
        } else {
            // 非胜利者显示失败对话框
            const defeatedDialog = document.getElementById('defeatedDialog');
            defeatedDialog.style.display = 'block';
            
            // 移除之前可能存在的事件监听器
            const returnButton = document.getElementById('returnToRoomListDefeated');
            returnButton.replaceWith(returnButton.cloneNode(true));
            
            // 重新获取新的按钮元素
            const newReturnButton = document.getElementById('returnToRoomListDefeated');
            
            // 添加返回房间列表按钮的点击事件
            newReturnButton.addEventListener('click', () => {
                console.log('玩家点击了返回按钮');
                // 通知服务器玩家离开房间
                socket.emit('leaveRoom', { roomId });
                defeatedDialog.style.display = 'none';
                window.location.href = '/rooms.html';
            });
        }
    });
    
    // 被击败
    world.on('defeated', () => {
        console.log('玩家被击败，显示对话框');
        // 显示被击败对话框
        const defeatedDialog = document.getElementById('defeatedDialog');
        defeatedDialog.style.display = 'block';
        
        // 移除之前可能存在的事件监听器
        const returnButton = document.getElementById('returnToRoomListDefeated');
        returnButton.replaceWith(returnButton.cloneNode(true));
        
        // 重新获取新的按钮元素
        const newReturnButton = document.getElementById('returnToRoomListDefeated');
        
        // 添加返回房间列表按钮的点击事件
        newReturnButton.addEventListener('click', () => {
            console.log('玩家点击了返回按钮');
            // 通知服务器玩家离开房间
            socket.emit('leaveRoom', { roomId });
            defeatedDialog.style.display = 'none';
            window.location.href = '/rooms.html';
        });
        
        // 阻止自动返回房间列表，只有当玩家点击按钮时才返回
        // 这样确保玩家能看到"你的坦克被击毁了"
    });
    
    // 开始游戏循环
    function startGameLoop() {
        let lastTime = 0;
        
        function gameLoop(timestamp) {
            // 计算时间差
            const deltaTime = timestamp - lastTime;
            lastTime = timestamp;
            
            // 更新游戏世界
            world.update(deltaTime);
            
            // 请求下一帧
            requestAnimationFrame(gameLoop);
        }
        
        // 启动游戏循环
        requestAnimationFrame(gameLoop);
    }
    
    // 返回房间列表按钮
    document.getElementById('backButton').addEventListener('click', () => {
        // 通知服务器玩家离开房间
        socket.emit('leaveRoom', { roomId });
        window.location.href = '/rooms.html';
    });
});